package com.knowswift.security.handler.success;

import com.knowswift.common.common.BaseResponse;
import com.knowswift.common.utils.JwtTokenUtils;
import com.knowswift.common.utils.WrappedBeanCopier;
import com.knowswift.security.account.User;
import com.knowswift.security.account.UserService;
import com.knowswift.security.account.UserVO;
import com.knowswift.security.handler.AbstractLoginSuccessHandler;
import com.knowswift.security.util.RedisUtils;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Date 2021/4/15
 **/

@Component
public class UserAppleLoginSuccessHandler extends AbstractLoginSuccessHandler {

    @Resource
    private UserService userService;

    @Resource
    private RedisUtils redisUtils;

    @Override
    public Object preAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {

        User user = (User) authentication.getPrincipal();
        if (user.getUserId() == null) {
            sendResponse(httpServletResponse, BaseResponse.NO_BIND_PHONE, "请先绑定手机号码", null);
            return null;
        }
        Map<String, Object> claims = new HashMap<>();
        user.setAppTokenVersion(user.getAppTokenVersion() + 1);
        userService.updateById(user);
        claims.put("tokenVersion", user.getAppTokenVersion());
        String token = JwtTokenUtils.generateToken(claims, user.getId());
        UserVO userVO = WrappedBeanCopier.copyProperties(user, UserVO.class);
        userVO.setToken(token);
        return userVO;
    }
}
